
const MD5 = require('md5');
const rp = require('request-promise');
const crypto = require('crypto');
const CryptoJs = require('crypto-js');

export class ReqUtils {
  async encryptUserInfoData(encryptedData) {
    // base64 decode
    const _sessionKey = process.env.aeskey;
    const defaultIv = '9189345332093662'; // 默认的key 偏移量

    let encode_encryptdata = '';
    let data = '';
    let encrypt = '';
    const keyStr = ReqUtils.encParse(_sessionKey);
    const ivStr = ReqUtils.encParse(defaultIv);
    // base64 decode
    encryptedData = encodeURIComponent(encryptedData);
    try {
      // 加密
      if (typeof encryptedData == 'string') {
        encrypt = ReqUtils.encParse(encryptedData);
      } else {
        data = JSON.stringify(encryptedData);
        encrypt = ReqUtils.encParse(data);
      }
      const encryptedStr = CryptoJs.AES.encrypt(encrypt, keyStr, {
        iv: ivStr,
        mode: CryptoJs.mode.CBC,
        padding: CryptoJs.pad.Pkcs7,
      });
      // 直接返回是 base64   128字节 encrypted.ciphertext.toString();
      encode_encryptdata = encryptedStr.toString();
    } catch (err) {
      console.log('encode_encryptdata', err);

      return '';
    }
    return encode_encryptdata;
  }

  static async decryptUserInfoData(encryptedData) {
    // base64 decode
    const _sessionKey = process.env.aeskey;
    const defaultIv = '9189345332093662'; // 默认的key 偏移量
    let decryptedStr = '';
    let decrypted = '';
    console.log(_sessionKey, '@@@@@@');

    try {
      // 解密
      const keyStr = ReqUtils.encParse(_sessionKey);
      const ivStr = ReqUtils.encParse(defaultIv);
      decrypted = encryptedData;
      const decoded = CryptoJs.AES.decrypt(decrypted, keyStr, {
        iv: ivStr,
        mode: CryptoJs.mode.CBC,
        padding: CryptoJs.pad.Pkcs7,
      });
      decryptedStr = decoded.toString(CryptoJs.enc.Utf8);
      console.log(_sessionKey, '@@@@@@', decryptedStr);
    } catch (err) {
      console.log(_sessionKey, '@@@@@@', err);
      return '';
    }
    return JSON.parse(decodeURIComponent(decryptedStr));
  }

  static serverNewParams(oldParams = {}) {
    let newParams = '';
    const MD5KEY = process.env.MD5KEY;
    const token = oldParams['token']; //读取
    const currentDate = new Date().getTime(); //获取到毫秒的时间戳，精确到毫秒
    const ip = oldParams['ip']; //读取
    newParams = '&timestamp=' + currentDate;
    let digestStr = currentDate + MD5KEY;
    if (token) {
      newParams += '&token=' + token;
      digestStr += token;
    }
    if (ip) {
      newParams += '&ip=' + ip;
      digestStr += ip;
    }
    newParams += '&sign=' + MD5(digestStr);

    return newParams;
  }
  static urltoObj(params: string): {} {
    const obj = {};

    const parr = params.split('&'); // 将参数分割成数组 ["id = 1 ", " type = 2"]
    for (const i of parr) {
      // 遍历数组
      if (i !== '') {
        const arr = i.split('='); // 1） i id = 1   arr = [id, 1]  2）i type = 2  arr = [type, 2]
        obj[arr[0]] = arr[1]; // obj[arr[0]] = id, obj.id = 1   obj[arr[0]] = type, obj.type = 2
      }
    }
    return obj;
  }

  static signParams(oldParams) {
    let newParams = '';
    const MD5KEY = process.env.MD5KEY;
    const token = oldParams['token']; //读取
    const currentDate = new Date().getTime(); //获取到毫秒的时间戳，精确到毫秒
    const timestamp = oldParams['timestamp']; //读取
    const ip = oldParams['ip']; //读取
    const sign = oldParams['sign']; //读取
    // $md5_str = $timestamp. $this->md5_key . $token . $appsFlyerId . $bundleId . $version . $platform;
    // 1648174746957hfu9CkqRMAVdhq2wnull1648173843216-9882120com.kkcash.thailand1.0.0ios
    let digestStr = '';
    if (timestamp) {
      newParams = oldParams + '&timestamp=' + timestamp;
      digestStr = timestamp + MD5KEY;
    } else {
      newParams = oldParams + '&timestamp=' + currentDate;
      digestStr = currentDate + MD5KEY;
    }
    if (token) {
      newParams += '&token=' + token;
      digestStr += token;
    } else {
      // console.log("无token");
    }
    if (ip) {
      newParams += '&ip=' + ip;
      digestStr += ip;
    } else {
      // console.log("无ip");
      // return false;
    }
    // console.log("sign:" + sign + " sign:", MD5(digestStr));

    if (sign == MD5(digestStr)) {
      return true;
    } else {
      return false;
    }
    // newParams +=
    //   "&sign=" +
    //   this.MD5(digestStr);

    // return newParams;
  }

  static jsonToParamsStr(json_params) {
    const params = Object.keys(json_params)
      .map(function (key) {
        // body...
        return (
          encodeURIComponent(key) + '=' + encodeURIComponent(json_params[key])
        );
      })
      .join('&');
    return params;
  }

  /*
   * 处理密钥字符格式
   */
  static encParse(key) {
    const keys = CryptoJs.enc.Utf8.parse(key);
    return keys;
  }
}
